package net.fireox.oa.comm.rtc.store;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

import net.fireox.oa.comm.rtc.entity.RTCMessage;
import net.fireox.oa.env.spring.SpringContext;
import net.fireox.oa.sys.security.SecurityHelper;


public class RTCMessageStore {
	
	private static Map<String, Queue<RTCMessage>> store = new ConcurrentHashMap<String, Queue<RTCMessage>>();
	
	public static void putMessage(RTCMessage msg){
		
		if(SecurityHelper.isOnline(msg.getReciever())){
			Queue<RTCMessage> msgs = store.get(msg.getReciever());
			
			if(msgs==null){
				msgs = new LinkedBlockingQueue<RTCMessage>();
			}
			
			msgs.add(msg);
			
			store.put(msg.getReciever(), msgs);
		}else{
			if(msg.isPersistable()){
				EntityManagerFactory emf = SpringContext.getBean("entityManagerFactory");
				
				EntityManager em = emf.createEntityManager();
				
				em.persist(msg);
			}
		}
	}
	
	public static List<RTCMessage> getMessages(String key){
		
		List<RTCMessage> msgs = new ArrayList<RTCMessage>();
		
		Queue<RTCMessage> queue = store.get(key);
		
		while(queue!=null&&queue.size()>0){
			msgs.add(queue.poll());
		}
		
		return msgs;
	}
}
